
//
// 120327 - AH - (Midtun) Created.
// 120715a- AH - Removed documented away code.
// 120715b- AH - Took PARENT_FOLDER_ID and FOLDER_NAME in use.
// 120728 - AH - Responds with array and not list as used to.
//

package org.soekrat.server.servlets.file;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.japril.servlet.HttpRequestDef;
import org.japril.servlet.HttpRequestParameter;
import org.soekrat.server.io.db.Folder;
import org.soekrat.server.io.db.SoekratDAO;
import org.soekrat.server.io.db.SoekratDAOFactory;
import org.soekrat.server.serialization.FolderSerializable;
import org.soekrat.server.servlets.AbstractSoekratHttpServlet;

/**
 * <p>
 *   Implements the request to get
 *   {@link Folder}s.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
@SuppressWarnings("serial")
public final class GetFoldersHttpServlet extends AbstractSoekratHttpServlet
{
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public GetFoldersHttpServlet(){}
  
  @Override
  protected void handleRequest(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    HttpRequestDef def=getHttpRequestDef();
    
    if (!hasParameters(req))
    {
      PrintWriter pw=printSimpleHtmlStart(res);
      pw.println(def.compileApiHtml());
      printSimpleHtmlEnd(pw);
      return;
    }
    
    if (!validate(res, def, req)) return;
    
    SoekratDAO dao=new SoekratDAOFactory().create();
    
    long owner=def.fetch(FOLDER_ID.name(), req).getLongValue();
    
    String name=def.fetch(FOLDER_NAME.name(), req).getStringValue();
    
    List<Folder> folders=dao.getFolders(owner, name);
    List<FolderSerializable> sfolders=new ArrayList<FolderSerializable>();
    for (Folder folder : folders) sfolders.add(new FolderSerializable(folder)); 
    respond(res, sfolders.toArray(FolderSerializable.EMPTY_ARRAY));
  }
  
  @Override
  public HttpRequestDef getHttpRequestDef()
  {
    HttpRequestDef retVal=new HttpRequestDef("/soekrat_server/get_folders")
      .desc("Get Folders").parameter(PARENT_FOLDER_ID);
    
    retVal.parameter(new HttpRequestParameter(FOLDER_NAME).mandatory(false));
    
    return retVal;
  }

}
